import axios from 'axios';
import md5 from 'crypto-js/md5';

const APP_KEY = '639aff9081092';
const APP_SECRET = '91225b65f6b7f3c1305f640823ad0721';
const BASE_URL = 'https://openapi.dataoke.com/api/goods/get-dtk-search-goods';

// 获取商品列表
export const getGoodsList = async (params) => {
  const timer = Date.now().toString(); // 毫秒级时间戳
  const nonce = generateNonce(); // 6位随机数
  const signRan = generateSign(timer, nonce); // 生成签名

  const response = await axios.get(BASE_URL, {
    params: {
      ...params,
      appKey: APP_KEY,
      nonce,
      timer,
      signRan
    },
  });

  return response.data;
};

// 生成6位随机数
const generateNonce = () => {
  return Math.floor(100000 + Math.random() * 900000).toString();
};

// 生成签名
const generateSign = (timer, nonce) => {
  // 拼接字符串
  const signStr = `appKey=${APP_KEY}&timer=${timer}&nonce=${nonce}&key=${APP_SECRET}`;
  // 生成MD5并转为大写
  return md5(signStr).toString().toUpperCase();
};